package Inventory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InventoryIn extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			String pid= req.getParameter("PID");
			int pquan= Integer.parseInt(req.getParameter("PQUANTITY"));
						
			Class.forName("org.h2.Driver");
			Connection con = DriverManager.getConnection("jdbc:h2:~/retail","sa", "");			
			PreparedStatement ps = con.prepareStatement("INSERT INTO INVENTORY VALUES(@ID,?,?,NOW())");
		    ps.setString(1, pid);
		    ps.setInt(2, pquan);		    
		    ps.executeUpdate();
		    
			PreparedStatement ps2 = 
					con.prepareStatement("UPDATE PRODUCT SET QUANTITY = QUANTITY + ? WHERE PRODUCTID = ?");
			ps2.setInt(1, pquan);
		    ps2.setString(2, pid);
		    		    
		    ps2.executeUpdate();		    		    		   
		    
		    ps.close();
			con.close();
			resp.sendRedirect("Inventory/InventoryMain.jsp");			
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (SQLException e) { 
			if(e.getErrorCode() == 90020){
				req.setAttribute("b", "錯誤"   );				
			}else{
				req.setAttribute("b", "SQL Exception:錯誤" );
			}				
			req.getRequestDispatcher("Inventory/InventoryError.jsp").forward(req, resp);							
		}catch (NumberFormatException e){
			req.setAttribute("b", "SQL Exception:輸入的不是數字");
			req.getRequestDispatcher("Inventory/InventoryError.jsp").forward(req, resp);		
		}		
		
	}

}
